import socket
import threading
import SocketServer

'''
Holy crap, I have *no* idea how any of this works.
'''
players = 0
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
    def __init__(self, *args, **kwargs):
        SocketServer.BaseRequestHandler.__init__(self, *args, **kwargs)

    def handle(self):
        data = self.request.recv(1024)
        cur_thread = threading.currentThread()
        if data == "get_player_id":
            global players
            print "Assigning player %s" % players
            response = "%s" % players
            players += 1
        else:
            response = "%s: %s" % (cur_thread.getName(), data)
        print "GOT SOME DATA"
        self.request.send(response)

class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    pass

class ServerHandler(object):
    def __init__(self, host, port):
        server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler)
        ip, port = server.server_address

        # Start a thread with the server -- that thread will then start one
        # more thread for each request
        server_thread = threading.Thread(target=server.serve_forever)
        # Exit the server thread when the main thread terminates
        server_thread.setDaemon(True)
        server_thread.start()
        print "DONE"

class ClientHandler(object):
    def __init__(self, ip, port):
        self.ip = ip
        self.port = port

    def send_message(self, message):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((self.ip, self.port))
        sock.send(message)
        response = sock.recv(1024)
        sock.close()
        return response
